﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using MemoryPack;
using UnityEditor;
using UnityEngine;

namespace Hsenl {
    public class MemoryPackRegisterUnionGen : HsenlScriptsGeneratorEditor {
        private const string _templatePath =
            "Assets/Plugins/HsenlFramework/Editor/HsenlScriptsGeneratorEditor/MemoryPackRegisterUnionGen/MemoryPackRegisterUnionTemplate.txt";

        private const string _outputDir = "Assets/Scripts/GameModel/Generate/MemoryPackUnionRegister";

        [MenuItem("Hsenl/ScriptsGenerator/生成自动注册MemoryPack Union的代码")]
        private static void Generate() {
            IOHelper.CleanDirectory(_outputDir);
            new MemoryPackRegisterUnionGen().ScriptsGenerate();
        }

        public override List<IHsenlScriptsGenerateScheme> GetSchemes() {
            List<IHsenlScriptsGenerateScheme> schemes = new();

            // 所有的类
            var allTypes = AppDomain.CurrentDomain.GetAssemblies().SelectMany(assembly => assembly.GetTypes()).ToArray();
            // 所有标记 MemoryPackableAttribute 的类
            var allMemoryPackableTypes = allTypes.Where(type => type.GetCustomAttribute<MemoryPackableAttribute>() != null).ToArray();
            // 所有 MemoryPackableAttribute 参数为 NoGenerate 的类, 这些类是需要注册 union 的
            var allRegisterTypes = allMemoryPackableTypes.Where(type => {
                var attr = type.GetCustomAttribute<MemoryPackableAttribute>();
                if (attr.GenerateType != GenerateType.NoGenerate)
                    return false;

                return true;
            }).ToArray();

            var allGenericTypes = allMemoryPackableTypes.Where(type => type.IsGenericType).ToArray();

            StringBuilder stringBuilder = new();
            foreach (var registerType in allRegisterTypes) {
                if (registerType.IsGenericType)
                    continue;
                
                stringBuilder.Append($"RegisterUnion<{registerType.Name}>();\n");
                stringBuilder.Append("          ");
            }

            // 没法
            UnityEngine.Debug.LogError(stringBuilder.ToString());

            return schemes;
            GenerateScheme_Replace scheme = new();
            scheme.templatePath = _templatePath;
            scheme.outputPath = $"{_outputDir}/MemoryPackFormatterGameModel.cs";
            // scheme.AddReplace("#CONTENT#", );
            schemes.Add(scheme);

            return schemes;
        }
    }
}